(function () {
	// 获取合同列表页面数据 服务器分页
    var serverData = {};
    var serverTable;//合同列表
    var serverSchedulingTable;
    var serverSchedulingData = {};
    jQuery(document).ready(function () {
    	
    	serverTable = jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/contract/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
                {
                	data: null
                },
                {
    	            data: null,
    	            defaultContent: "",
    	            render: function (data, type, full, meta) {
    	            	var id=data.id
    	            	var operate ='<input type="checkbox" class="checkchildContract">';
    	            	return operate;
    	            }   
                },
                {
                    data: 'supplierCode'
                },
                {
                	data: 'contractType'
                },
                {
                	data: 'state'
                },
                {
                    data: 'cstate'
                },
                /*{
                    data: 'totalSum'
                },*/
                {
                    data: 'scheduleDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data: 'signedDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data: 'giveOutDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data: 'deliveryDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data: 'debugDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data: 'acceptanceDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                /*{
                    data: 'stop'
                },
                {
                    data: 'freightCharge'
                },*/
                {
                    data: 'projectName'
                },
                {
                    data: 'orderUnit'
                },
                {
                    data: 'orderAddress'
                },
                {
                    data: 'orderDelegate'
                },
                {
                    data: 'orderPhone'
                },
                {
                    data: 'orderZip'
                },
                {
                    data: 'orderArea'
                },
                {
                    data: 'postUnit'
                },
                {
                    data: 'postAddress'
                },
                {
                    data: 'postDelegate'
                },
                {
                    data: 'postPhone'
                },
                {
                    data: 'postZip'
                }
                ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }
            }
        });
    	serverSchedulingData.state="新增";
    	serverSchedulingTable = jQuery('#SchedulingTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "iDisplayLength": 5,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/scheduling/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverSchedulingData);
                }
            },
            columns: [
                {
                	data: null
                },
                {
    	            data: null,
    	            defaultContent: "",
    	            render: function (data, type, full, meta) {
    	            	var id=data.id
    	            	var operate ='<input type="checkbox" class="checkchildCruxDate">';
    	            	return operate;
    	            }   
                },
                {
                	data: 'cPlanNumber'
                },
                {
                    data: 'cContractNumber'
                },
                {
                    data: 'cState'
                },
                {
                	data: 'dIssuedDate',
                	render: function (data, type, full, meta) {
                		if (data)
                			return moment(data).format('YYYY/MM/DD');
                		else
                			return '';
                	}
                },
                {
                	data: 'cType'
                },
                {
                	data: 'contractInfo.signedDate',
                	render: function (data, type, full, meta) {
                		if (data)
                			return moment(data).format('YYYY/MM/DD');
                		else
                			return '';
                	}
                },
                {
                	data: 'dDeliveryDate',
                	render: function (data, type, full, meta) {
                		if (data)
                			return moment(data).format('YYYY/MM/DD');
                		else
                			return '';
                	}
                },
                {
                	data: 'cUserUnit'
                },
                {
                	data: 'cMemo',
                	render:function(data,type,full,meta){
  	                	if(data == null || data == undefined || data == ""){
  							return data;
  						}else{
  							return (data.length > 18) ? '<font title="'+data+'">'+data.substring(0,18)+'...'+'</font>' : data;
  						}
  					}
                },
                {
                	data: 'user.name'
                },
                {
                	data: 'cCreateDept'
                },
                {
                	data: 'dCreateDate',
                	render: function (data, type, full, meta) {
                		if (data)
                			return moment(data).format('YYYY/MM/DD');
                		else
                			return '';
                	}
                },
                {
                	data: 'nPrintCount'
                },
                {
                	data: 'nPrintDate',
                	render: function (data, type, full, meta) {
                		if (data)
                			return moment(data).format('YYYY/MM/DD');
                		else
                			return '';
                	}
                }
                ],
                "drawCallback": function (oSettings) {
                    var k = 0;
                    var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                    for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                        $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                        k++;
                    }
                }
        });
    	// 生成计划任务
    	jQuery('.schedulingBtn').on('click', function () {
    		   var selects=getSelect("#dataTable",1);
    		   if(selects.length==0){
    		       $.springLemonDialog({
    		         content: '请选择生成计划的合同',// 确认文本
    		         clickButton: function (sender, modal, index) {// 按钮事件处理
    		             $(this).closeDialog(modal);
    		         }
    		       }); 
    		   }else if(selects.length > 1){
    		       $.springLemonDialog({
      		         content: '请只能选择一条合同生成计划',// 确认文本
      		         clickButton: function (sender, modal, index) {// 按钮事件处理
      		             $(this).closeDialog(modal);
      		         }
      		       }); 
      		   }else{
    			   var flag = false;
    			   var ids=selects[0].contractId;
    			   var types=selects[0].contractType;
    			   var totalSum=selects[0].totalSum;
    			   if((selects[0].cstate=='未排产' || selects[0].cstate==null) && (selects[0].opPlanTaskId == null || selects[0].opPlanTaskId == "")){
    				   flag = true;
    			   }
    			   for(var i=1;i<selects.length;i++){
    				   ids += ',' + selects[i].contractId;  
    				   types += ',' + selects[i].contractType;
    				   if((selects[i].cstate=='未排产' || selects[i].cstate==null) && (selects[0].opPlanTaskId == null || selects[0].opPlanTaskId == "")){
        				   flag = true;
        			   }
    			   }
    			   if (flag==false){
    				   $.springLemonDialog({
    	    		         content: '存在已生成计划任务的合同，请重新选择！',// 确认文本
    	    		         clickButton: function (sender, modal, index) {// 按钮事件处理
    	    		             $(this).closeDialog(modal);
    	    		         }
    	    		       });
   	    	   	       return;
    			   }
    			   var urlxy = window.rootPath + '/ui/contract/checkMoney?contractId=' + ids + '&totalSum=' + totalSum;
    			   jQuery.ajax({
    	               	type : 'get',
    	               	url : encodeURI(urlxy),
    	               	dataType : 'json',
    	               	contentType : 'application/json;charset=utf-8',
    	               	success : function(data) {
    	               		if(data==0){
    	               			$.springLemonDialog({
    	               				content: '确认生成'+selects.length+'条计划任务？',// 确认文本
    	               				clickButton: function (sender, modal, index) {// 按钮事件处理
    	               					if (index == 0) {
    	               						var url=window.rootPath+"/ui/scheduling/generationplan"+"?contractInfo="+ ids +":"+ types;
    	               						jQuery.ajax({
    	               							url:encodeURI(url),
    	               							cache:false,
    	               							type : "get",
    	               							dataType:"json",
    	               							success:function(data){
    	               								if(data==0){
    	               									alert("合同录入细目不完整！");
    	               								}
    	               								if(data==1){
    	               									alert("选中合同中有已经生成过计划任务的数据");
    	               								}
    	               								if(data==2){
    	               									alert("生成过计划任务成功！");
    	               								}
    	               								serverTable.draw();
    	               								serverSchedulingTable.draw();
    	               							}
    	               						});
    	               					}
    	               					$(this).closeDialog(modal);
    	               				}
    	               			});  
    	               		} else if(data==1){
    	               			alert("合同金额小于细目的总金额，不能生成计划任务！");
    	               		} else if(data==2){
    	               			alert("合同金额大于细目的总金额，不能生成计划任务！");
    	               		}
    	               	}
	               });
    		   }
    		});
    	// 生成计划任务
    	jQuery('#updateschedulingBtn').on('click', function () {
    		   var selects=getSelect("#SchedulingTable",1);
    		   if(selects.length==0){
    		       $.springLemonDialog({
    		         content: '请选择计划任务',// 确认文本
    		         clickButton: function (sender, modal, index) {// 按钮事件处理
    		             $(this).closeDialog(modal);
    		         }
    		       }); 
    		   }else{
    			   var flag = false;
    			   var ids=selects[0].id;
    			   //var types=selects[0].contractType;
    			   for(var i=1;i<selects.length;i++){
    				   ids += ',' + selects[i].id;
    			   }
    			   $.springLemonDialog({
    			         content: '确认提取选中计划任务的合同信息？',// 确认文本
    			         clickButton: function (sender, modal, index) {// 按钮事件处理
    			        	 if (index == 0) {
    			        		 var url=window.rootPath+"/ui/scheduling/UpdatePlan"+"?schedulingIds="+ ids;
    		                        jQuery.ajax({
    		                            url:encodeURI(url),
    		                            cache:false,
    		                            type : "get",
    		                            dataType:"json",
    		                            success:function(data){
    		                            	if(data==0){
    		                            		alert("该计划任务未找到！");
    		                            	}
    		                            	if(data==1){
    		                            		alert("提取合同信息成功！");
    		                            	}
    		                                //serverTable.draw();
    		                                serverSchedulingTable.draw();
    		                            }
    		                        });
    			        	 }
    			             $(this).closeDialog(modal);
    			         }
    			       });  
    		   }
    		});
    	// 删除计划
    	jQuery('#delSchedulingBtn').on('click', function () {
    		var selects=getSelect("#SchedulingTable",1);
    		if(selects.length==0){
    			$.springLemonDialog({
    				content: '请选择删除的计划任务',// 确认文本
    				clickButton: function (sender, modal, index) {// 按钮事件处理
    					$(this).closeDialog(modal);
    				}
    			}); 
    		}else{
    			var flag = true;
    			var ids=selects[0].id;
    			var userId = jQuery('#userId').val();
				if (selects[0].cState != '新增' || userId != selects[0].user.id) {
    				flag = false;
    			}
    			for(var i=1;i<selects.length;i++){
    				ids += ',' + selects[i].id;  
					if (selects[0].cState != '新增'|| userId != selects[0].user.id ) {
    					flag = false;
    				}
    			}
    			if (flag==false){
    				$.springLemonDialog({
    					content: '您只能删除新增且自己的计划任务！',// 确认文本
    					clickButton: function (sender, modal, index) {// 按钮事件处理
    						$(this).closeDialog(modal);
    					}
    				});
    				return;
    			}
    			$.springLemonDialog({
    				content: '确认删除'+selects.length+'条计划任务？',// 确认文本
    				clickButton: function (sender, modal, index) {// 按钮事件处理
    					if (index == 0) {
    						var url=window.rootPath+"/ui/scheduling/deletePlanTask"+"?schedulingIds="+ ids;
    						jQuery.ajax({
    							url:encodeURI(url),
    							cache:false,
    							type : "delete",
    							dataType:"json",
    							success:function(data){
    								if(data==1){
    									alert("只能删除自己的计划任务！");
    								}else if(data==2){
    									alert("未找到该计划任务！");
	    							}else if(data==0){
	    								serverTable.draw();
	    								serverSchedulingTable.draw();
	    								$("#checkAllContract").prop("checked", false);
	    							}
    							}
    						});
    					}
    					$(this).closeDialog(modal);
    				}
    			});  
    		}
    	});
        
    	// 查看计划
    	jQuery('#seeSchedulingBtn').on('click', function () {
    		var selects=getSelect("#SchedulingTable",1);
    		if(selects.length>1){
    			$.springLemonDialog({
    				content: '只能查看一条计划任务',// 确认文本
    				clickButton: function (sender, modal, index) {// 按钮事件处理
    					$(this).closeDialog(modal);
    				}
    			}); 
    		}
    		else if(selects.length==0){
    			$.springLemonDialog({
    				content: '请选择要查看的计划任务',// 确认文本
    				clickButton: function (sender, modal, index) {// 按钮事件处理
    					$(this).closeDialog(modal);
    				}
    			}); 
    		}else if(selects.length==1){
    			var cstate = selects[0].cState;
    			var userId = jQuery('#userId').val();
				var id=selects[0].id;
				var url=window.rootPath+"/ui/scheduling/schedulingEdit/"+ id + "/see";
				window.location.href = url;
    		}
    	});
        // 修改计划
    	jQuery('#editSchedulingBtn').on('click', function () {
    	       var selects=getSelect("#SchedulingTable",1);
    		   if(selects.length>1){
    			   $.springLemonDialog({
    			         content: '只能编辑一条计划任务',// 确认文本
    			         clickButton: function (sender, modal, index) {// 按钮事件处理
    			             $(this).closeDialog(modal);
    			         }
    			   }); 
    		   }
    		   else if(selects.length==0){
    			   $.springLemonDialog({
    			         content: '请选择要编辑的计划任务',// 确认文本
    			         clickButton: function (sender, modal, index) {// 按钮事件处理
    			             $(this).closeDialog(modal);
    			         }
    			   }); 
    		   }else if(selects.length==1){
    			    var cstate = selects[0].cState;
    			    var userId = jQuery('#userId').val();
					if (cstate != '新增') {
						$.springLemonDialog({
							content : '该计划任务状态不是新增，只能查看',// 确认文本
							clickButton : function(sender, modal, index) {// 按钮事件处理
								if (index == 0) {
		    						var id=selects[0].id;
		    						var url=window.rootPath+"/ui/scheduling/schedulingEdit/"+ id + "/see";
		    		    			window.location.href = url;
		    					}
								$(this).closeDialog(modal);
							}
						});
					} else if (userId != selects[0].user.id) {
						$.springLemonDialog({
							content : '您只能修改自己的计划任务',// 确认文本
							clickButton : function(sender, modal, index) {// 按钮事件处理
								$(this).closeDialog(modal);
							}
						});
					} else {
						var id=selects[0].id;
		    			var url=window.rootPath+'/ui/scheduling/schedulingEdit/'+ id + "/up" ;
		    			window.location.href = url;
					}
    			   
    		   }
    		});
    	// 打印计划
    	jQuery('#printSchedulingBtn').on('click', function () {
    		var selects=getSelect("#SchedulingTable",1);
    		if(selects.length>1){
    			$.springLemonDialog({
    				content: '只能打印一条计划任务',// 确认文本
    				clickButton: function (sender, modal, index) {// 按钮事件处理
    					$(this).closeDialog(modal);
    				}
    			}); 
    		}
    		else if(selects.length==0){
    			$.springLemonDialog({
    				content: '请选择要打印的计划任务',// 确认文本
    				clickButton: function (sender, modal, index) {// 按钮事件处理
    					$(this).closeDialog(modal);
    				}
    			}); 
    		}else if(selects.length==1){
    			var cstate = selects[0].cState;
				var id=selects[0].id;
				var url = null;
				if(selects[0].contractInfo.contractType=="备件合同")
					url=window.rootPath+'/ui/scheduling/printBJScheduling?id='+ id ;
				else
					url=window.rootPath+'/ui/scheduling/printscheduling?id='+ id ;
				window.location.href = url;
    		}
    	});
    	
        
        // 提交计划任务
        jQuery('#IssuedSchedulingBtn').on('click', function () {
        	var selects=getSelect("#SchedulingTable",1);
    		if(selects.length==0){
    			$.springLemonDialog({
    				content: '请选择下达的计划任务',// 确认文本
    				clickButton: function (sender, modal, index) {// 按钮事件处理
    					$(this).closeDialog(modal);
    				}
    			}); 
    		}else{
    			var flag = true;
    			var ids=selects[0].id;
    			var userId = jQuery('#userId').val();
				if (selects[0].cState != '新增' || userId != selects[0].user.id || selects[0].cLowStockMemo ==null) {
    				flag = false;
    			}
    			for(var i=1;i<selects.length;i++){
    				ids += ',' + selects[i].id;  
					if (selects[0].cState != '新增'|| userId != selects[0].user.id || selects[0].cLowStockMemo ==null) {
    					flag = false;
    				}
    			}
    			if (flag==false){
    				$.springLemonDialog({
    					content: '您只能下达新增或者降库说明不能为空或者自己的计划任务！',// 确认文本
    					clickButton: function (sender, modal, index) {// 按钮事件处理
    						$(this).closeDialog(modal);
    					}
    				});
    				return;
    			}
    			$.springLemonDialog({
    				content: '确认下达'+selects.length+'条计划任务？',// 确认文本
    				clickButton: function (sender, modal, index) {// 按钮事件处理
    					if (index == 0) {
    						var url=window.rootPath+"/ui/scheduling/issuedplan"+"?schedulingIds="+ ids;
    						jQuery.ajax({
    							url:encodeURI(url),
    							cache:false,
    							type : "post",
    							dataType:"json",
    							success:function(data){
    								serverSchedulingTable.draw();
    								$("#checkAllContract1").prop("checked", false);
    							}
    						});
    					}
    					$(this).closeDialog(modal);
    				}
    			});  
    		}
        });
        // 计划任务列表中的查询
        $(".searchBtn1").click(function(){
        	var key = jQuery('#keyword1').val();
        	serverSchedulingData.key = key;
        	serverSchedulingData.state = jQuery('#state').val();
        	serverSchedulingTable.draw();
    	});
        $(".resetBtn1").click(function(){
        	jQuery('#keyword1').val("");
        	serverSchedulingData.key = "";
        	serverSchedulingData.state = jQuery('#state').val();
        	serverSchedulingTable.draw();
        });
        jQuery('#state').change(function(){
        	serverSchedulingData.key=jQuery("#keyword1").val();
	    	var state=jQuery('#state').val();
	    	serverSchedulingData.state=state;
	    	serverSchedulingTable.draw();
		});
        
        // 合同列表中的查询
        $(".searchBtn").click(function(){
        	var key = jQuery('#keyword').val();
        	serverData.key = key;
        	serverTable.draw();
        });
        $(".resetBtn").click(function(){
        	jQuery('#keyword').val("");
        	serverData.key = "";
        	serverTable.draw();
        });
        
        // 合同列表中的全选
        $("#checkAllContract").click(function(){
        	var check = $(this).prop("checked");
            $(".checkchildContract").prop("checked", check);
    	});
        
        // 计划任务列表中的全选
        $("#checkAllContract1").click(function(){
        	var check = $(this).prop("checked");
            $(".checkchildContract1").prop("checked", check);
    	});
        
        // 收回
        jQuery("#takeSchedulingBtn").on('click',function() {
            var selects = getSelect("#SchedulingTable", 1);
            if (selects.length == 0) {
                $.springLemonDialog({
                    content: '请选择要收回的计划',// 确认文本
                    clickButton: function (sender, modal, index) {// 按钮事件处理
                        $(this).closeDialog(modal);
                    }
                });
            } else if (selects.length > 0) {
                
            	var flag = true;
    			var ids=selects[0].id;
    			var userId = jQuery('#userId').val();
    			if (selects[0].cState != '下达' || userId != selects[0].user.id ) {
    				flag = false;
    			}
    			for(var i=1;i<selects.length;i++){
    				ids += ',' + selects[i].id;  
    				if (selects[0].cState != '下达'|| userId != selects[0].user.id) {
    					flag = false;
    				}
    			}
    			if (flag==false){
    				$.springLemonDialog({
    					content: '您只能收回下达且自己的计划任务！',// 确认文本
    					clickButton: function (sender, modal, index) {// 按钮事件处理
    						$(this).closeDialog(modal);
    					}
    				});
    				return;
    			}
            	
                jQuery.springLemonDialog({
                    content: '确认收回' + selects.length + '条计划？',// 确认文本
                    clickButton: function (sender, modal, index) {
                    	if (index == 0) {
    						var url=window.rootPath+"/ui/scheduling/regainPlanTask"+"?schedulingIds="+ ids;
    						jQuery.ajax({
    							url:encodeURI(url),
    							cache:false,
    							type : "get",
    							dataType:"json",
    							success:function(data){
    								if(data==0){
    									serverSchedulingTable.draw();
    									$("#checkAllContract1").prop("checked", false);
    								}else if(data==1){
    									alert("计划任务未找到！");
    								}else if(data==2){
    									alert("只能收回自己的计划任务！");
    								}
    							}
    						});
    					}
    					$(this).closeDialog(modal);
                    }
                });
            }//end of if
        });
        
    });
    
	
    
    
})();